package com.zuimei.zuimei.utils;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.zuimei.zuimei.MyApp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 本地缓存
 */

public class LocalCacheUtil {
    private static String CACHE_PATH;

    public LocalCacheUtil(Context context) {
       // Context context = new MyApp().getContext();
        //手机的缓存空间，存在这里的缓存文件会随着手机被卸载而清除掉
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            CACHE_PATH = context.getExternalCacheDir().getAbsolutePath();
        } else {
            CACHE_PATH = context.getCacheDir().getAbsolutePath();
        }
    }

    /**
     * 从本地获取数据
     */
    public String getJsonStringFromLocal(String url) {
        String result = null;
        String fileName = MD5Util.MD5(url);
        File file = new File(CACHE_PATH, fileName);
        if (file.exists()) {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new FileReader(file));
                String validTime = br.readLine();// 读取第一行内容,缓存截止时间
                if (System.currentTimeMillis() < Long.parseLong(validTime)) {// 当前时间小于缓存截止时间,缓存有效
                    StringBuffer sb = new StringBuffer();
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                    result = sb.toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return result;
    }

    /**
     * 向本地存数据
     */
    public void setJsonStringToLocal(String url, String jsonString) {
        FileWriter fw = null;
        String fileName = MD5Util.MD5(url);
        assert fileName != null;
        File file = new File(CACHE_PATH, fileName);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        try {
            fw = new FileWriter(file);
            // 缓存有效期限, 截止时间设定为半小时之后
            long validTime = System.currentTimeMillis() + 30 * 60 * 1000;
            fw.write(validTime + "\n");// 将缓存截止时间写入文件第一行
            fw.write(jsonString);
            fw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 清除本地缓存
     */
    public void clearLocalCache(String url) {
        String fileName = MD5Util.MD5(url);
        if (!TextUtils.isEmpty(fileName)) {
            File file = new File(CACHE_PATH, fileName);
            if (file.exists()) {
                boolean delete = file.delete();
                if (delete) {
                    Log.d("TAG", "删除成功");
                }
            }
        }
    }
}
